package com.cxs.videoplayer.provider;

import com.cxs.videoplayer.ResourceTable;
import com.cxs.videoplayer.data.DeviceInfo;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.List;

public class DeviceListProvider extends BaseItemProvider {

    List<DeviceInfo> deviceInfoList;
    DeviceClickedListener deviceClickedListener;

    public DeviceListProvider(List<DeviceInfo> deviceInfoList) {
        this.deviceInfoList = deviceInfoList;
    }

    public void setDeviceClickedListener(DeviceClickedListener deviceClickedListener) {
        this.deviceClickedListener = deviceClickedListener;
    }

    @Override
    public int getCount() {
        return deviceInfoList == null ? 0 : deviceInfoList.size();
    }

    @Override
    public Object getItem(int i) {
        if (deviceInfoList != null && deviceInfoList.size() > 0) {
            return deviceInfoList.get(i);
        }
        return null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        final Component cpt;
        ViewHolder viewHolder;
        if (component == null) {
            cpt = LayoutScatter.getInstance(componentContainer.getContext())
                    .parse(ResourceTable.Layout_device_list_item, null, false);
            viewHolder = new ViewHolder(cpt);
            cpt.setTag(viewHolder);
        } else {
            cpt = component;
            viewHolder = (ViewHolder)cpt.getTag();
        }
        if (viewHolder != null) {
            DeviceInfo deviceInfo = deviceInfoList.get(i);
            viewHolder.deviceType.setText(deviceInfo.getType());
            // 点击设备的回调
            viewHolder.deviceType.setClickedListener(c -> {
                deviceClickedListener.onClicked(deviceInfo.getId());
            });
        }
        return cpt;
    }

    private static class ViewHolder {
        Text deviceType;

        public ViewHolder(Component component) {
            deviceType = (Text)component.findComponentById(ResourceTable.Id_device_type);
        }
    }

    public interface DeviceClickedListener {
        void onClicked(String deviceId);
    }
}
